package com.whut.dao.impl;


import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;
import javax.mail.MessagingException;

import org.apache.naming.java.javaURLContextFactory;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.mapping.Map;
import org.junit.Test;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.stereotype.Component;

import com.sun.net.httpserver.Authenticator.Success;
import com.whut.dao.UserDao;
import com.whut.model.User;
import com.whut.util.UtilCommon;
import com.whut.vo.UserRegisterInfo;

@Component("userDao")
public class UserDaoImpl implements UserDao {
	
	private HibernateTemplate hibernateTemplate;
	
	//获取现在时间
 	SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");	
	Date nowDate = new Date();
	
	public HibernateTemplate getHibernateTemplate() {
		return hibernateTemplate;
	}
    @Resource(name="hibernateTemplate")
	public void setHibernateTemplate(HibernateTemplate hibernateTemplate) {
		this.hibernateTemplate = hibernateTemplate;
	}    
    
	@Override
	public void save(User u) {
		//添加注册时间regDate
//		String regDate = simpleDateFormat.format(nowDate);	     
//		u.setRegDate(regDate);
		
		//利用注册的验证码经过MD5加密作为emailCode
//		String emailCode = UtilCommon.md5Encryption(u.getEmailCode());
//		u.setEmailCode(emailCode);
		
		//利用hibernateTemplate保存User对象
		hibernateTemplate.save(u);
		
	}
	
	@Override
	public void save(UserRegisterInfo info) {
		//利用hibernateTemplate保存注册对象
		hibernateTemplate.save(info);
		
	}

	@Override
	public boolean checkUserWithName(String username) {
		// TODO Auto-generated method stub
		List<User> users=hibernateTemplate.find("from User u where u.username='"+username+"'");
		if(users.size()>0 && users != null)
			return true;
		else 
			return false;
	}
	
	@Override
	public boolean checkUser(String username, String password) {
		List<User> users=hibernateTemplate.find("from User u where u.username='"+username+"'and u.password='"+password+"'");
		if(users.size()>0 && users != null)
			return true;
		else 
			return false;
	}
	
	@Override
	public List<User> getUsers() {
		// TODO Auto-generated method stub
		return (List<User>)hibernateTemplate.find("from User");
	}
		
	//往数据库修改loginTimes项
	@Override
	public void addLoginTimes(User u) {		
		//查询数据库中的loginTimesInData	
		List<Integer> loginTimesInData = (List)hibernateTemplate.find("SELECT u.loginTimes FROM User u where u.username='"+u.getUsername()+"'");		
		System.out.println(loginTimesInData.get(0));
		
		//每登录一次，loginTimes加1 
		int loginTimes = loginTimesInData.get(0)+1;
		
		//取出id
		List<Integer> id = (List)hibernateTemplate.find("SELECT u.id FROM User u where u.username='"+u.getUsername()+"'");
		System.out.println(id.get(0));
				
		String lastDate = simpleDateFormat.format(nowDate);
	    
		//采用session的方式只更新loginTimes的值
		Session session = hibernateTemplate.getSessionFactory().openSession();    //只能用openSession的方式
		session.beginTransaction();  
		Query query = session.createQuery("update User u set loginTimes='"+loginTimes+"',lastDate='"+lastDate+"'where u.id='"+id.get(0)+"'");  
		query.executeUpdate();  
		session.getTransaction().commit(); 
		session.close();    //必须显示关闭session
	} 	
		
	
	//每次登录，返回用户等级信息
	@Override
	public int checkPriority(User u) {
		List<Integer> priorityList = (List)hibernateTemplate.find("SELECT u.priority FROM User u where u.username='"+u.getUsername()+"'");		
		int priorityInData = priorityList.get(0);
		System.out.println("数据库中priority:"+priorityInData);
		return priorityInData;
	}
	
	
	 
 
	//分页查找
	public List findByPage(final String hql, final int offset, final int pageSize){   
        List list = hibernateTemplate.executeFind(new HibernateCallback() {   
               
            public Object doInHibernate(Session session) {   
                List result = session.createQuery(hql).setFirstResult(offset)   
                                .setMaxResults(pageSize)   
                                .list(); 
                System.out.println(result);
                return result;   
            }   
        });   
        return list;   
    }   
	
	//获取User表的总数
	@Override
	public Long count(String hql) throws Exception {
		// TODO Auto-generated method stub			
		List<Long> countNum = (List)hibernateTemplate.find(hql);		
		return countNum.get(0);
	} 
 
	//更新某对象的某id的全部信息
	@Override
	public void update(Object o) throws Exception {
		this.hibernateTemplate.update(o);
	}
	
	//移除某对象的某id的全部信息
	@Override
	public void delete(Object o) throws Exception {
		this.hibernateTemplate.delete(o);
	}
	
	@Override
	public List<User> find(int id) {
		// TODO Auto-generated method stub
				
		return (List<User>)hibernateTemplate.find("from User u  where u.id =" + id);
	}
	
}


/*	
@Override
public String checkEmalCode(User u, String emailCode) {
	//查询数据库中的loginTimesInData	
	System.out.println(u.getUsername());
	List<String> emailCodeList = (List)hibernateTemplate.find("SELECT u.emailCode FROM User u where u.username='"+u.getUsername()+"'");		
	String emailCodeInData = emailCodeList.get(0);		
	System.out.println("数据库中emailCode:"+emailCodeInData);
	
	if(this.checkEmalStatus(u)) {
		System.out.println("邮箱已验证");
		return "alreadyAtive";
	}else if(emailCodeInData != null &&emailCodeInData.equals(emailCode)) {
		System.out.println("邮箱激活成功");
		//取出id
		List<Integer> id = (List)hibernateTemplate.find("SELECT u.id FROM User u where u.username='"+u.getUsername()+"'");
		System.out.println(id.get(0));
		
		//采用session的方式只更新emailStatus的值
		Session session = hibernateTemplate.getSessionFactory().openSession();    //只能用openSession的方式
		session.beginTransaction();  
		Query query = session.createQuery("update User u set emailStatus=1 where u.id='"+id.get(0)+"'");  
		query.executeUpdate();  
		session.getTransaction().commit(); 
		session.close();    //必须显示关闭session
		return "success";
	}
	else {
		System.out.println("邮箱激活失败,验证码过期");
		return "fail";
		
	}
	
}

//每次登录，检查邮箱是否已验证
@Override
public boolean checkEmalStatus(User u) {
	List<Integer> emailStatusList = (List)hibernateTemplate.find("SELECT u.emailStatus FROM User u where u.username='"+u.getUsername()+"'");		
	int emailStatusInData = emailStatusList.get(0);
	System.out.println("数据库中emailStatus:"+emailStatusInData);
	if(emailStatusInData == 1) {
		System.out.println("用户邮箱已验证");
		return true;
	} else {
		System.out.println("用户邮箱未验证");
		return false;
	}
}*/